package com.codeduck.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.codeduck.business.domain.BusinessBO;
import com.codeduck.business.domain.BusinessRes;
import com.codeduck.business.service.IBusinessService;
import com.codeduck.common.dubbo.IOrderDubboService;
import com.codeduck.common.dubbo.IStorageDubboService;
import com.codeduck.common.enums.MicroExceptionEnum;
import com.codeduck.common.enums.ResEnum;
import com.codeduck.common.exception.MicroException;
import com.codeduck.common.response.OrderResponse;
import com.codeduck.common.response.ServiceResponse;
import com.codeduck.common.response.StorageResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @createDate: 2022-08-20
 */
@Service
@Slf4j
public class BusinessServiceImpl implements IBusinessService {

    @Resource
    private IStorageDubboService storageDubboService;

    @Resource
    private IOrderDubboService orderDubboService;

    @Override
    public BusinessRes handleBusiness(BusinessBO businessBO) {
        log.info("交易信息 = [{}]", JSON.toJSONString(businessBO));

        // 1. 扣减库存
        ServiceResponse<StorageResponse> storageServiceResponse =
                storageDubboService.decreaseStorage(businessBO.getCommodityCode(), businessBO.getCount());

        // 2. 创建订单
        ServiceResponse<OrderResponse> orderServiceResponse =
                orderDubboService.createOrder(businessBO.getUserId(), businessBO.getCommodityCode(), businessBO.getCount());

        // 3.判断服务是否调用成功
        if (null == storageServiceResponse ||storageServiceResponse.getCode().equals(ResEnum.FAILED.getCode())
                || null == orderServiceResponse || orderServiceResponse.getCode().equals(ResEnum.FAILED.getCode())) {
            throw new MicroException(MicroExceptionEnum.PRC_ERROR.getMessage());
        }
        BusinessRes businessRes = BusinessRes.builder()
                .commodityCode(orderServiceResponse.getData().getCommodityCode())
                .money(orderServiceResponse.getData().getAmount())
                .orderNo(orderServiceResponse.getData().getOrderNo())
                .userId(businessBO.getUserId())
                .build();

        return businessRes;
    }
}
